package com.hs.biye.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hs.biye.constant.MessageConstant;
import com.hs.biye.excepction.BaseException;
import com.hs.biye.mapper.DepartmentMapper;
import com.hs.biye.mapper.EmployeeMapper;
import com.hs.biye.mapper.RoomMapper;
import com.hs.biye.model.DTO.MedicineRequest;
import com.hs.biye.model.DTO.RegnusRequest;
import com.hs.biye.model.VO.PatientVo;
import com.hs.biye.model.VO.RegnusVo;
import com.hs.biye.model.entity.*;
import com.hs.biye.model.enums.GenderEnum;
import com.hs.biye.model.reslut.ResultPage;
import com.hs.biye.service.RegistrationService;
import com.hs.biye.service.RegnusService;
import com.hs.biye.mapper.RegnusMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author haoshuai
* @description 针对表【regnus】的数据库操作Service实现
* @createDate 2024-02-21 20:12:56
*/
@Service
public class RegnusServiceImpl extends ServiceImpl<RegnusMapper, Regnus>
    implements RegnusService {

    @Resource
    private RegnusMapper regnusMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private RegistrationService registrationService;

    @Resource
    private RoomMapper roomMapper;






    @Override
    public ResultPage<RegnusVo> getPageRegnus(RegnusRequest regnusRequest) {

        if (regnusRequest == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }
        Integer page = regnusRequest.getPages();
        Integer size = regnusRequest.getSize();
        IPage<Regnus> page2 = new Page<>(page, size);
        regnusMapper.selectPage(page2, getQueryWrapper(regnusRequest));
        List<Regnus> records = page2.getRecords();
        long total = page2.getTotal();
        long current = page2.getCurrent();
        long pages = page2.getPages();

        List<RegnusVo> list = new ArrayList<>();

        records.forEach(item -> {
            RegnusVo regnusVo = new RegnusVo();
            BeanUtils.copyProperties(item, regnusVo);
            Employee employee = employeeMapper.selectById(item.getEmployeeId());
            regnusVo.setEmployeeName(employee.getEmployeeName());

            Department department = departmentMapper.selectById(item.getDepartmentId());
            regnusVo.setDepartmentName(department.getDepartmentName());
            list.add(regnusVo);

        });
        return ResultPage.success(list, total, current, pages);


    }

    @Override
    public Boolean addReRegnus(RegnusRequest regnusRequest) {
        if (regnusRequest == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }

        Regnus regnus = new Regnus();
        BeanUtils.copyProperties(regnusRequest,regnus);

        return save(regnus);
    }

    @Override
    public Boolean updateReRegnus(RegnusRequest regnusRequest) {
        if (regnusRequest == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }
        Regnus regnus = new Regnus();
        BeanUtils.copyProperties(regnusRequest,regnus);
        return updateById(regnus);
    }

    @Override
    public Boolean deleteReRegnus(RegnusRequest regnusRequest) {
        if (regnusRequest == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }
        LambdaQueryWrapper<Regnus> queryWrapper = getQueryWrapper(regnusRequest);
        if (regnusRequest.getRegNusId() == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }
        queryWrapper.eq(Regnus::getRegNusId, regnusRequest.getRegNusId());
        return remove(queryWrapper);
    }

    @Override
    public RegnusVo getRegnusByid(Integer id) {
        if (id == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }
        Regnus regnus = getById(id);
        RegnusVo regnusVo = new RegnusVo();
        BeanUtils.copyProperties(regnus,regnusVo);
        return regnusVo;
    }


    //根据科室id查询可以挂号的医生  todo 可以加入时间查询条件 默认查询明天的医生
    @Override
    public List<RegnusVo> regdoctors(Integer id,String date) {
        if (id == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }

        System.out.println("--------------");
        System.out.println(date);
        LocalDate localDate = null;
        if (date ==null || date==""){
            System.out.println("123");
            LocalDate now = LocalDate.now();
            localDate = now.plusDays(1);
        }else {
            System.out.println("456");
            localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        List<Regnus> regnuses = baseMapper.selectList(new LambdaQueryWrapper<Regnus>()
                .eq(Regnus::getDepartmentId, id)
                .eq(Regnus::getUseTime,localDate)
                .gt(Regnus::getAmNumber, 0)
                .gt(Regnus::getPmNumber, 0));
        List<RegnusVo> res = new ArrayList<>();
        regnuses.forEach(i->{
            RegnusVo regnusVo = new RegnusVo();
            BeanUtils.copyProperties(i,regnusVo);
            Employee employee = employeeMapper.selectById(i.getEmployeeId());
            regnusVo.setEmployeeName(employee.getEmployeeName());
            res.add(regnusVo);
        });
        return  res;
    }


    //确定挂号
    @Override
    @Transactional
    public Boolean guahao(Integer id, Integer sign,Integer patientId) {
        if (id == null || sign==null || patientId == null) {
            throw new BaseException(MessageConstant.PAR_NOT_RIGHT);
        }
        String time ="";
        Regnus regnus = getById(id);
        if (sign == 0){
            Integer amNumber = regnus.getAmNumber();
            if (amNumber > 0){
                regnus.setAmNumber(amNumber-1);
                time = "上午";
            }else {
                throw new BaseException("");
            }

        }else {
            Integer pmNumber = regnus.getPmNumber();
            if (pmNumber > 0){
                regnus.setPmNumber(pmNumber-1);
                time = "下午";
            }else {
                throw new BaseException("");
            }
        }
        boolean update = updateById(regnus);
        if (update){
            //查询部门名称和就诊室id
            Employee employee = employeeMapper.selectById(regnus.getEmployeeId());
            Department department = departmentMapper.selectById(employee.getDepartmentId());
            Room room = roomMapper.selectOne(new LambdaQueryWrapper<Room>().eq(Room::getDoctorId, employee.getEmployeeId()));

            //记录挂号信息
            Registration registration = new Registration();
            registration.setRoomId(room.getRoomId());
            registration.setDepartmentName(department.getDepartmentName());
            registration.setDoctorId(regnus.getEmployeeId());
            registration.setPatientId(patientId);
            registration.setUseTime(regnus.getUseTime());
            // registration.setIsDeal();
            registration.setTime(time);
            Boolean res = registrationService.addRegistration(registration);
            return res;
        }
        return false;
    }


    private LambdaQueryWrapper<Regnus> getQueryWrapper(RegnusRequest regnusRequest){

        LambdaQueryWrapper<Regnus> queryWrapper = new LambdaQueryWrapper<>();
        Integer regNusId = regnusRequest.getRegNusId();
        Integer employeeId = regnusRequest.getEmployeeId();
        LocalDate useTime = regnusRequest.getUseTime();
        Integer departmentId = regnusRequest.getDepartmentId();
        String employeeName = regnusRequest.getEmployeeName();

        List<Integer> ids = null;
        if (employeeName !=null){
            LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.select(Employee::getEmployeeId)
                    .eq(ObjectUtil.isNotEmpty(employeeName),Employee::getEmployeeName,employeeName);
            List<Employee> employees = employeeMapper.selectList(queryWrapper1);
            ids = employees.stream().map(m -> m.getEmployeeId()).collect(Collectors.toList());
        }


        queryWrapper.in(!CollectionUtils.isEmpty(ids),Regnus::getEmployeeId,ids);
        queryWrapper.eq(ObjectUtil.isNotEmpty(useTime),Regnus::getUseTime,useTime);
        queryWrapper.eq(ObjectUtil.isNotEmpty(departmentId),Regnus::getDepartmentId,departmentId);
        //排序
        // employeeQueryWrapper.orderBy(true,true,Employee::getCreateTime);
        return queryWrapper;
    }

}




